//
//  JYBaseWebViewController.m
//  RHappy
//
//  Created by Stephen on 2018/3/22.
//  Copyright © 2018年 Stephen. All rights reserved.
//

#import "JYBaseWebViewController.h"

@interface JYBaseWebViewController () <UIWebViewDelegate>

@property (nonatomic, strong) WebViewBlock  webBlock;

@end

@implementation JYBaseWebViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGTH-64)];
    webView.tag = 999;
    webView.delegate = self;
    if (self.htmlStr) {
        [webView loadHTMLString:self.htmlStr baseURL:nil];
    } else if (self.urlStr){
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_urlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
        [webView loadRequest:request];
    } else {
        NSURLRequest *request = [NSURLRequest requestWithURL:self.url];
        [webView loadRequest:request];
    }
    [self.view addSubview:webView];
    [self showTextHUDWithStr:@"加载中"];
}

-(void)viewWillDisappear:(BOOL)animated{
    [self cleanCacheAndCookie];
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *URL = request.URL;
    NSString *scheme = [NSString stringWithFormat:@"%@", URL];
    NSLog(@"当前跳转地址111111：%@",scheme);
    if ([scheme containsString:@"loginPage"] || [scheme containsString:@"baidu.com"]) {
        if ([self.urlStr containsString:@"repaymentId"] || [self.urlStr containsString:@"applyId"]) {
            [self showTextHUDWithStr:@"加载中"];
            NSString *str = [[scheme componentsSeparatedByString:@"no="] lastObject];
            WS(weakSelf);
            NSInteger type = 2;
            if ([self.urlStr containsString:@"applyId"]) {
                type = 1;
            }
            [self uploadSignInfoWithType:type applyNo:str andWithBlock:^{
                [weakSelf popViewController];
            }];
            return NO;
        }else{
            [self popViewController];
        }
        return YES;
    }
    return YES;
}

-(void)popViewController{
    [self.navigationController popToRootViewControllerAnimated:YES];
    if (self.webBlock) {
        self.webBlock(YES);
    }
}

- (void)webViewIsQianSuccess:(WebViewBlock)isSuccess {
    self.webBlock = isSuccess;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *script = [NSString stringWithFormat:
                        @"var script = document.createElement('script');"
                        "script.type = 'text/javascript';"
                        "script.text = \"function ResizeImages() { "
                        "var img;"
                        "var maxwidth=%f;"
                        "for(i=0;i <document.images.length;i++){"
                        "img = document.images[i];"
                        "if(img.width > maxwidth){"
                        "img.width = maxwidth;"
                        "}"
                        "}"
                        "}\";"
                        "document.getElementsByTagName('head')[0].appendChild(script);", SCREEN_WIDTH - 20];
    [webView stringByEvaluatingJavaScriptFromString: script];
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];

    [self hideTextHud];
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [self hideTextHud];
}

- (void)cleanCacheAndCookie{
    //清除cookies
    NSHTTPCookie *cookie;NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}
    

#pragma mark 上传签约截图

-(void)uploadSignInfoWithType:(NSInteger)type applyNo:(NSString *)applyNo andWithBlock:(void(^)(void))block{
    UIImage *image = [CommonTools imageWithScreenContentsInView:[self.view viewWithTag:999]];
    
//    [JYBaseModel uploadImageWithUrl:@"" parame:@{@"type":[NSNumber numberWithInteger:type],@"userId":[UserModel shareModel].userId,@"applyNo":applyNo,@"signStatus":[NSNumber numberWithInteger:1]} data:@[@[image]] dataName:@[@"file"] completHandle:^(JYResponds *result) {
//        [MBProgressHUD hideHUD];
//        if (result.isSuccess) {
//            [MBProgressHUD showSuccess:result.resultDesc];
//            block();
//        }else{
//            [MBProgressHUD showError:result.resultDesc];
//        }
//    }];
}


@end
